package multiple_status;

/**
 * 引用计数销毁对象
 */
class Shared {
    private static int counter = 0;
    private final int id = counter ++;
    private static int refCount = 0;

    public Shared() {
        System.out.println("create: " + this);
    }

    public void addRef() {
        refCount ++;
    }

    public void dispose() {
        if(-- refCount == 0)
            System.out.println("dispose: " + this);
    }

    @Override
    public String toString() {
        return "Shared " + id;
    }
}

class A {
    private Shared shared;
    private static int counter = 0;
    private final int id = counter ++;

    public A(Shared shared) {
        this.shared = shared;
        shared.addRef();
        System.out.println("create: " + this);
    }

    public void dispose() {
        System.out.println("dispose: " + this);
        shared.dispose();
    }

    @Override
    public String toString() {
        return "A " + id;
    }
}

public class Test {
    public static void main(String[] args) {
        Shared shared = new Shared();
        A a1 = new A(shared);
        A a2 = new A(shared);
        A a3 = new A(shared);
        A a4 = new A(shared);

        a1.dispose();
        a2.dispose();
        a3.dispose();
        a4.dispose();
    }
}
